<?php
declare (strict_types = 1);
namespace app\common\middleware;
use app\common\Token;  //jwt token 验证  
use app\admin\model\Shop;
// use think\facade\Log;
class CheckToken
{
	  /**
	     * 处理请求 token 验证  
	     *
	     * @param \think\Request $request
	     * @param \Closure       $next
	     * @return Response
	     */
	  public function handle($request, \Closure $next)
	  {		
	  	 	
	  	 	
	  	 	$root = $request->root();
	  	 	$pathinfo = $request->pathinfo();

	  	 	$nochk = [   //不校验登录的接口 
	  	 		'/api/common/clickCaptcha',
	  	 		'/api/common/checkClickCaptcha',
	  	 		'/api/index/index'
	  	 	];
	  	 	$path_arr = explode("/",$pathinfo);
 			$store = trim($request->header('token') ?? '');
		    if(empty($store)){
		    	//Log::record('未绑定店铺');
		        return json(['error_code'=>102,'msg'=>"未绑定店铺"],400);
		    }
		    
		    $request->shop_id = Shop::where("token",$store)->value("sid");

	  	 	if(in_array($root.'/'.$pathinfo,$nochk) || $path_arr[0] == 'Xcx'){
	  	 		  return $next($request);
	  	 	}
		    //第一步先取token / Authorization 
		    $token = trim($request->header('Authorization') ?? '');
		    
		    //jwt进行校验token
		    if(empty($token)){
		    	  return json(['error_code'=>101,'msg'=>"未登录"],400);
		    }
	        $jie =  Token::verifyToken($token);

	        if($jie['code'] == 1){
	               $data = $jie['data'];
	               $request->uid = $data->uid;
	        }else{
	        	  return json(['error_code'=>102,'msg'=>$jie['msg']],400);
	        }
		    return $next($request);
	  }
}
